<template>
  <div>
    <el-dialog :title="currentTitle" :visible.sync="dialogFormVisible">
      <el-form :model="formData" v-loading="isLoading">
        <el-form-item label="角色名称" :label-width="formLabelWidth">
          <el-input v-model="formData.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="授权名称" :label-width="formLabelWidth">
          <el-input v-model="formData.authorizeName" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="isLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import {AddRoles, getOneRoles, UpdateRoles} from "@/api/roles/roles";

export default {
  name: "UpdateCreateRoles",
  computed: {
    currentTitle() {
      return this.isCreate ? '添加角色' : '编辑角色'
    }
  },
  data() {
    return {
      //false加载完成  true未加载完成
      isLoading: false,
      //创建 true false是编辑
      isCreate: true,
      dialogFormVisible: false,
      formData: {
        id: undefined,
        roleName: '',
        authorizeName: ''
      },
      singleData: {
        id: undefined,
      },
      formLabelWidth: '120px'
    }
  },
  methods: {
    showAndInit(roleId) {
      //!roleId true是新建   false是编辑
      this.isCreate = !roleId;
      this.dialogFormVisible = true;
      //新建
      if (this.isCreate) {
        //表单清空
        this.formData = {}

      }
      //编辑
      else {
        this.isLoading = true
        this.singleData.id = roleId;
        //回显当前角色信息
        getOneRoles(this.singleData).then(res => {
          const {id, roleName, authorizeName} = res.data.data;
          this.formData = {id, roleName, authorizeName}
        }).finally(() => {
          //加载完成
          this.isLoading = false;
        })


      }
    },
    onSubmit(){
      if (this.isCreate) {
        AddRoles(this.formData).then(res=>{
          if (res.data.code == '200') {
            this.$message.success(`${this.currentTitle}角色成功!`)
            //向父组件发送消息(自定义事件)
            this.$emit('changeRoles')
            this.dialogFormVisible=false;
          } else {
            this.$message.error(`${this.currentTitle}角色失败!`)
          }
        })
      }else {
        UpdateRoles(this.formData).then(res=>{
          if (res.data.code == '200') {
            this.$message.success(`${this.currentTitle}角色成功!`)
            //向父组件发送消息(自定义事件)
            this.$emit('changeRoles')
            this.dialogFormVisible=false;
          } else {
            this.$message.error(`${this.currentTitle}角色失败!`)
          }
        })
      }
    }
  }
}
</script>
<style scoped>

</style>
